package com.bootdo.market.controller;

import com.bootdo.common.utils.*;
import com.bootdo.market.dao.CommonDao;
import com.bootdo.market.domain.ProductChannelProfitDO;
import com.bootdo.market.service.ProductChannelProfitService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.bootdo.common.utils.ShiroUtils.getUser;

/**
 * 渠道数据收益统计
 *
 * @author jinse
 * @email market@jinse.com
 * @date 2019-07-25 17:22:48
 */

@Controller
@RequestMapping("/market/productChannelProfit")
public class ProductChannelProfitController {
    @Autowired
    private ProductChannelProfitService productChannelProfitService;
    @Autowired
    private CommonDao commonDao;

    @GetMapping()
    @RequiresPermissions("market:productChannelProfit:productChannelProfit")
    String ProductChannelProfit() {
        return "market/productChannelProfit/productChannelProfit";
    }

    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("market:productChannelProfit:productChannelProfit")
    public PageUtils list(@RequestParam Map<String, Object> params) {
        //查询列表数据
        Query query = new Query(params);
        List<ProductChannelProfitDO> productChannelProfitList = productChannelProfitService.list(query);
        productChannelProfitList.stream().forEach(productChannelProfitDO -> {
            productChannelProfitDO.setProductDomain(productChannelProfitDO.getProductDomain() + "?ch_id=" + productChannelProfitDO.getChannelid() + "&linkname=" + productChannelProfitDO.getLinkname());

            productChannelProfitDO.setRate(productChannelProfitDO.getChannelsettlementrate() == null ? "" : productChannelProfitDO.getChannelsettlementrate() + ":" + (productChannelProfitDO.getPlatformsettlementrate() == null ? "" : productChannelProfitDO.getPlatformsettlementrate()));
        });
        int total = productChannelProfitService.count(query);
        PageUtils pageUtils = new PageUtils(productChannelProfitList, total);
        return pageUtils;
    }

    @GetMapping("/add")
    @RequiresPermissions("market:productChannelProfit:add")
    String add() {
        return "market/productChannelProfit/add";
    }

    @GetMapping("/edit/{id}")
    @RequiresPermissions("market:productChannelProfit:edit")
    String edit(@PathVariable("id") Integer id, Model model) {
        ProductChannelProfitDO productChannelProfit = productChannelProfitService.get(id);
        model.addAttribute("productChannelProfit", productChannelProfit);
        return "market/productChannelProfit/edit";
    }

    /**
     * 保存
     */
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("market:productChannelProfit:add")
    public R save(ProductChannelProfitDO productChannelProfit) {
        if (productChannelProfitService.save(productChannelProfit) > 0) {
            return R.ok();
        }
        return R.error();
    }

    /**
     * 修改
     */
    @ResponseBody
    @RequestMapping("/update")
    @RequiresPermissions("market:productChannelProfit:edit")
    public R update(ProductChannelProfitDO productChannelProfit) {
        if (productChannelProfit.getChannelsettlementamount() == null) {
            if ("1".equals(productChannelProfit.getSettlementmethod())) {
                BigDecimal result_num_new = new BigDecimal(String.format("%.2f", Double.valueOf(String.valueOf(productChannelProfit.getAdvertiseruv())) * Double.valueOf(String.valueOf(productChannelProfit.getSettlementprice()))));
                productChannelProfit.setChannelsettlementamount(result_num_new);
            } else if ("2".equals(productChannelProfit.getSettlementmethod())) {
                BigDecimal result_num_new = new BigDecimal(String.format("%.2f", Double.valueOf(String.valueOf(productChannelProfit.getAdvertiserpv())) / 1000 * Double.valueOf(String.valueOf(productChannelProfit.getSettlementprice()))));
                productChannelProfit.setChannelsettlementamount(result_num_new);
            } else if ("3".equals(productChannelProfit.getSettlementmethod())) {
                BigDecimal result_num_new = new BigDecimal(String.format("%.2f", Double.valueOf(String.valueOf(productChannelProfit.getChannelsettlementrate())) / 100 * Double.valueOf(String.valueOf(productChannelProfit.getPlatformprofit()))));
                productChannelProfit.setChannelsettlementamount(result_num_new);
            }
        }
        BigDecimal ecpm = new BigDecimal(String.format("%.2f", Double.valueOf(String.valueOf(productChannelProfit.getPlatformprofit())) * 1000 / Double.valueOf(String.valueOf(productChannelProfit.getAdvertiserpv()))));
        productChannelProfit.setPlatformecpm(ecpm);

        BigDecimal arup = new BigDecimal(String.format("%.5f", Double.valueOf(String.valueOf(productChannelProfit.getPlatformprofit())) / Double.valueOf(String.valueOf(productChannelProfit.getAdvertiseruv()))));
        productChannelProfit.setPlatformarup(arup);

        BigDecimal pv = new BigDecimal(String.format("%.0f", Double.valueOf(String.valueOf(productChannelProfit.getAdvertiserpv())) * Double.valueOf(String.valueOf(100 - productChannelProfit.getOptparameters())) / 100));
        productChannelProfit.setShowchannelpv(pv.intValue());

        BigDecimal uv = new BigDecimal(String.format("%.0f", Double.valueOf(String.valueOf(productChannelProfit.getAdvertiseruv())) * Double.valueOf(String.valueOf(100 - productChannelProfit.getOptparameters())) / 100));
        productChannelProfit.setShowchanneluv(uv.intValue());

        BigDecimal netprofit = new BigDecimal(String.format("%.2f", Double.valueOf(String.valueOf(productChannelProfit.getPlatformprofit())) - Double.valueOf(String.valueOf(productChannelProfit.getChannelsettlementamount()))));
        productChannelProfit.setPlatformnetprofit(netprofit);

        productChannelProfitService.update(productChannelProfit);
        return R.ok();
    }

    /**
     * 删除
     */
    @PostMapping("/remove")
    @ResponseBody
    @RequiresPermissions("market:productChannelProfit:remove")
    public R remove(ProductChannelProfitDO productChannelProfit) {
        productChannelProfitService.update(productChannelProfit);
        return R.ok();

    }

    /**
     * 删除
     */
    @PostMapping("/batchRemove")
    @ResponseBody
    @RequiresPermissions("market:productChannelProfit:batchRemove")
    public R remove(@RequestParam("ids[]") Integer[] ids) {
        for (int i = 0; i < ids.length; i++) {
            ProductChannelProfitDO productChannelProfit = new ProductChannelProfitDO();
            productChannelProfit.setId(ids[i]);
            productChannelProfit.setPublishstate(1);
            productChannelProfitService.update(productChannelProfit);
        }
        return R.ok();
    }

    @RequestMapping(value = "/exportExcel")
    @RequiresPermissions("market:productChannelProfit:exportExcel")
    public void exportExcel
            (String beginTime,
             String endTime,
             String productid,
             String channelid,
             String linkname,
             String publishstate,
             HttpServletRequest request,
             HttpServletResponse response) throws Exception {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("productid", productid);
        params.put("channelid", channelid);
        params.put("linkname", linkname);
        if (StringUtils.isNotBlank(publishstate)) {
            params.put("publishstate", 1);
        }
        if (StringUtils.isNotBlank(beginTime)) {
            params.put("beginTime", beginTime);
        } else {
            params.put("beginTime", null);
        }
        if (StringUtils.isNotBlank(endTime)) {
            params.put("endTime", endTime);
        } else {
            params.put("endTime", null);
        }
        List<ProductChannelProfitDO> list = commonDao.listProductChannelProfitDO(params);

        List<Object[]> objects = new ArrayList<>();
        if (null != list && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                Object[] obj = new Object[30];
                ProductChannelProfitDO taDTO = list.get(i);
                obj[0] = taDTO.getHistorydate();
                obj[1] = taDTO.getChannelid();
                obj[2] = taDTO.getChannelname();
                obj[3] = taDTO.getProductname();
                obj[4] = taDTO.getLinkname();
                obj[5] = taDTO.getProductDomain();
                obj[6] = taDTO.getAdvertiserpv();

                obj[7] = taDTO.getAdvertiseruv();
                obj[8] = taDTO.getPlatformprofit();
                obj[9] = taDTO.getPlatformecpm();
                obj[10] = taDTO.getPlatformarup();

                if ("1".equals(taDTO.getSettlementmethod())) {
                    obj[11] = "UV";
                } else if ("2".equals(taDTO.getSettlementmethod())) {
                    obj[11] = "CPM";
                } else if ("3".equals(taDTO.getSettlementmethod())) {
                    obj[11] = "CPS";
                } else {
                    obj[11] = "";
                }
                obj[12] = taDTO.getSettlementprice();

                obj[13] = taDTO.getRate();
                obj[14] = taDTO.getOptparameters();
                if (taDTO.getPublishstate() == 1) {
                    obj[15] = "已发布";
                } else {
                    obj[15] = "'未发布'";
                }
                obj[16] = taDTO.getShowchannelpv();
                obj[17] = taDTO.getShowchanneluv();
                obj[18] = taDTO.getChannelsettlementamount();

                obj[19] = taDTO.getPlatformnetprofit();


                SimpleDateFormat formatter = new SimpleDateFormat(DateUtil.DATE_TIME_FORMAT);
                obj[20] = formatter.format(taDTO.getCreatetime());
                objects.add(obj);
            }
        }
        Map<Object, List<Object[]>> dataMap = new LinkedHashMap<Object, List<Object[]>>();
        dataMap.put(new Object(), objects);
        String title = "渠道数据统计";
        String[] headers = {"日期", "渠道ID", "渠道名称", "产品名称", "链接名称", "产品链接", "广告主PV",
                "广告主UV", "平台收入", "平台eCPM", "平台arup值", "结算方式", "结算价格", "结算比例",
                "优化参数", "发布状态", "PV", "UV", "结算金额", "平台净利润", "更新时间",
        };
        SXSSFWorkBookUtil.exportSheetsForOneObj(title, headers, dataMap,
                request, response);
    }

    @RequestMapping(value = "/channelexportExcel")
    @RequiresPermissions("market:productChannelProfit:channelexportExcel")
    public void channelexportExcel
            (String beginTime,
             String endTime,
             String productid,
             String channelid,
             String linkname,
             String publishstate,
             HttpServletRequest request,
             HttpServletResponse response) throws Exception {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("productid", productid);
        params.put("channelid", channelid);
        params.put("linkname", linkname);
        if (StringUtils.isNotBlank(publishstate)) {
            params.put("publishstate", 1);
        }
        if (StringUtils.isNotBlank(beginTime)) {
            params.put("beginTime", beginTime);
        } else {
            params.put("beginTime", null);
        }
        if (StringUtils.isNotBlank(endTime)) {
            params.put("endTime", endTime);
        } else {
            params.put("endTime", null);
        }
        List<ProductChannelProfitDO> list = commonDao.listProductChannelProfitDO(params);

        List<Object[]> objects = new ArrayList<>();
        if (null != list && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                Object[] obj = new Object[30];
                ProductChannelProfitDO taDTO = list.get(i);
                obj[0] = taDTO.getHistorydate();
                obj[1] = taDTO.getLinkname();
                obj[2] = taDTO.getProductDomain();
                obj[3] = taDTO.getShowchannelpv();
                obj[4] = taDTO.getShowchanneluv();
                obj[5] = taDTO.getChannelsettlementamount();
                objects.add(obj);
            }
        }
        Map<Object, List<Object[]>> dataMap = new LinkedHashMap<Object, List<Object[]>>();
        dataMap.put(new Object(), objects);
        String title = "渠道数据统计";
        String[] headers = {"日期","链接名称", "产品链接", "PV", "UV", "结算金额",
        };
        SXSSFWorkBookUtil.exportSheetsForOneObj(title, headers, dataMap,
                request, response);
    }

    //todo 渠道方所看到的的数据
    @GetMapping("/channelSidelistJsp")
    @RequiresPermissions("market:productChannelProfit:channelSidelistJsp")
    String channelSidelistJsp(Model model) {
        model.addAttribute("channelid", getUser().getChannelid());
        return "market/productChannelProfit/channelSideproductChannelProfit";
    }

    @ResponseBody
    @GetMapping("/channelSidelist")
    @RequiresPermissions("market:productChannelProfit:channelSidelist")
    public PageUtils channelSidelist(@RequestParam Map<String, Object> params) {
        if (getUser().getChannelstatus() != null && getUser().getChannelstatus() == 2) {
            params.put("channelid", getUser().getChannelid());
            params.put("publishstate", 1);
            //查询列表数据
            Query query = new Query(params);
            List<ProductChannelProfitDO> productChannelProfitList = productChannelProfitService.list(query);
            productChannelProfitList.stream().forEach(productChannelProfitDO -> {
                productChannelProfitDO.setProductDomain(productChannelProfitDO.getProductDomain() + "?ch_id=" + productChannelProfitDO.getChannelid() + "&linkname=" + productChannelProfitDO.getLinkname());
                productChannelProfitDO.setRate(productChannelProfitDO.getChannelsettlementrate() == null ? "" : productChannelProfitDO.getChannelsettlementrate() + ":" + (productChannelProfitDO.getPlatformsettlementrate() == null ? "" : productChannelProfitDO.getPlatformsettlementrate()));
            });
            int total = productChannelProfitService.count(query);
            PageUtils pageUtils = new PageUtils(productChannelProfitList, total);
            return pageUtils;
        }
        return new PageUtils(new ArrayList<>(), 0);
    }
}
